package com.example.picturestorage.mapper;

import com.example.picturestorage.bean.Book;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author 28116
 */
@Mapper
@CacheNamespace(flushInterval = 60)
@Repository
public interface BookMapper {

    /**
     * 懒加载为eager
     *
     * @return list
     */
    @Select(value = "select * from tb_book")
    @Results(id = "book",
            value = {
                    @Result(property = "id", column = "id", id = true),
                    @Result(property = "bookName", column = "book_name"),
                    @Result(property = "publishDate", column = "publish_date"),
                    @Result(property = "path",column = "path"),
                    @Result(property = "publisher", column = "publisher_id",
                            one = @One(select = "com.example.picturestorage.mapper.PublisherMapper.findPublisherById", fetchType = FetchType.EAGER))
            })
    List<Book> findAllBook();

    @Select(value = "select * from tb_book where publisher_id = #{publisherId}")
    @Results(id = "book2",
            value = {
                    @Result(property = "id", column = "id", id = true),
                    @Result(property = "bookName", column = "book_name"),
                    @Result(property = "publishDate", column = "publish_date")
            })
    List<Book> findAllBookByPubId(String publisherId);

    @Insert("insert into tb_book(book_name,publish_date,path,price,amount,publisher_id) values(#{bookName},#{publishDate},#{path},#{price},#{amount},#{publisher.id})")
    @Options(useGeneratedKeys = true,keyProperty = "id")
    int addBook(Book book);

    /**
     * 删除所有表数据
     *
     */
    @Delete("truncate tb_book")
    void deleteAllBook();

    /**
     * 通过对象查询书籍
     *
     * @param book Book对象
     * @return Book
     */
    @Select("select * from tb_book where id=#{book.id}")
    @ResultMap("book")
    Book findBookById(@Param("book") Book book);

    /**
     * 通过id删除书籍
     *
     * @param id 书籍id
     *
     */
    @Delete("delete from tb_book where id = #{id}")
    void deleteBookById(Integer id);

    @Delete("delete from tb_book where id > #{id}")
    void deleteBookOverId(Integer id);

    @Select("select b.id,book_name bookName,p.name 'publisher.name'," +
            "p.id 'publisher.id' from tb_book b join tb_publisher p" +
            " on b.publisher_id=p.id and b.id=#{bookId}")
    @Options(flushCache = Options.FlushCachePolicy.TRUE)
    Book findBookWithPublisherByBookId(Integer bookId);

}
